import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import {
  Settings,
  User,
  Shield,
  Bell,
  Database,
  Mail,
  Globe,
  Lock,
  Key,
  Server,
  Monitor,
  Palette,
  Languages,
  Clock,
  Save,
  RefreshCw,
  Download,
  Upload,
  Trash2,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Info
} from 'lucide-react';

/**
 * 系统配置接口定义
 */
interface SystemConfig {
  // 基本设置
  siteName: string;
  siteDescription: string;
  adminEmail: string;
  timezone: string;
  language: string;
  
  // 安全设置
  enableTwoFactor: boolean;
  sessionTimeout: number;
  passwordPolicy: {
    minLength: number;
    requireUppercase: boolean;
    requireNumbers: boolean;
    requireSymbols: boolean;
  };
  
  // 通知设置
  emailNotifications: boolean;
  smsNotifications: boolean;
  pushNotifications: boolean;
  
  // 系统设置
  maintenanceMode: boolean;
  debugMode: boolean;
  logLevel: string;
  backupFrequency: string;
}

/**
 * 模拟系统配置数据
 */
const mockSystemConfig: SystemConfig = {
  siteName: '企业管理系统',
  siteDescription: '高效的企业级后台管理解决方案',
  adminEmail: 'admin@company.com',
  timezone: 'Asia/Shanghai',
  language: 'zh-CN',
  enableTwoFactor: true,
  sessionTimeout: 30,
  passwordPolicy: {
    minLength: 8,
    requireUppercase: true,
    requireNumbers: true,
    requireSymbols: false
  },
  emailNotifications: true,
  smsNotifications: false,
  pushNotifications: true,
  maintenanceMode: false,
  debugMode: false,
  logLevel: 'info',
  backupFrequency: 'daily'
};

/**
 * 系统状态数据
 */
const systemStatus = {
  uptime: '15天 8小时 32分钟',
  cpuUsage: 45,
  memoryUsage: 68,
  diskUsage: 32,
  activeUsers: 127,
  totalRequests: 1234567,
  errorRate: 0.02,
  responseTime: 245
};

/**
 * 系统设置页面主组件
 */
export default function SettingsPage() {
  const [config, setConfig] = useState<SystemConfig>(mockSystemConfig);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('general');
  const [showBackupDialog, setShowBackupDialog] = useState(false);

  /**
   * 保存配置
   */
  const handleSaveConfig = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      toast.success('配置保存成功');
    } catch (error) {
      toast.error('保存配置失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 重置配置
   */
  const handleResetConfig = () => {
    setConfig(mockSystemConfig);
    toast.success('配置已重置');
  };

  /**
   * 创建备份
   */
  const handleCreateBackup = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 2000));
      toast.success('系统备份创建成功');
      setShowBackupDialog(false);
    } catch (error) {
      toast.error('创建备份失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 获取状态颜色
   */
  const getStatusColor = (value: number, type: 'usage' | 'rate') => {
    if (type === 'usage') {
      if (value < 50) return 'text-green-600';
      if (value < 80) return 'text-yellow-600';
      return 'text-red-600';
    } else {
      if (value < 0.01) return 'text-green-600';
      if (value < 0.05) return 'text-yellow-600';
      return 'text-red-600';
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-6xl mx-auto space-y-6">
        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">系统设置</h1>
            <p className="text-gray-600 mt-1">管理系统配置和安全设置</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" onClick={handleResetConfig}>
              <RefreshCw className="w-4 h-4 mr-2" />
              重置配置
            </Button>
            <Button onClick={handleSaveConfig} disabled={loading}>
              <Save className="w-4 h-4 mr-2" />
              {loading ? '保存中...' : '保存配置'}
            </Button>
          </div>
        </div>

        {/* 系统状态概览 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">系统运行时间</p>
                  <p className="text-lg font-bold text-gray-900">{systemStatus.uptime}</p>
                </div>
                <Clock className="w-8 h-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">CPU使用率</p>
                  <p className={`text-lg font-bold ${getStatusColor(systemStatus.cpuUsage, 'usage')}`}>
                    {systemStatus.cpuUsage}%
                  </p>
                </div>
                <Monitor className="w-8 h-8 text-green-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">内存使用率</p>
                  <p className={`text-lg font-bold ${getStatusColor(systemStatus.memoryUsage, 'usage')}`}>
                    {systemStatus.memoryUsage}%
                  </p>
                </div>
                <Database className="w-8 h-8 text-yellow-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">活跃用户</p>
                  <p className="text-lg font-bold text-gray-900">{systemStatus.activeUsers}</p>
                </div>
                <User className="w-8 h-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 设置选项卡 */}
        <Card>
          <CardContent className="p-6">
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="grid w-full grid-cols-5">
                <TabsTrigger value="general">基本设置</TabsTrigger>
                <TabsTrigger value="security">安全设置</TabsTrigger>
                <TabsTrigger value="notifications">通知设置</TabsTrigger>
                <TabsTrigger value="system">系统设置</TabsTrigger>
                <TabsTrigger value="backup">备份管理</TabsTrigger>
              </TabsList>

              {/* 基本设置 */}
              <TabsContent value="general" className="space-y-6 mt-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="siteName">站点名称</Label>
                      <Input
                        id="siteName"
                        value={config.siteName}
                        onChange={(e) => setConfig(prev => ({ ...prev, siteName: e.target.value }))}
                        placeholder="请输入站点名称"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="adminEmail">管理员邮箱</Label>
                      <Input
                        id="adminEmail"
                        type="email"
                        value={config.adminEmail}
                        onChange={(e) => setConfig(prev => ({ ...prev, adminEmail: e.target.value }))}
                        placeholder="请输入管理员邮箱"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="timezone">时区设置</Label>
                      <Select value={config.timezone} onValueChange={(value) => setConfig(prev => ({ ...prev, timezone: value }))}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="Asia/Shanghai">Asia/Shanghai (UTC+8)</SelectItem>
                          <SelectItem value="America/New_York">America/New_York (UTC-5)</SelectItem>
                          <SelectItem value="Europe/London">Europe/London (UTC+0)</SelectItem>
                          <SelectItem value="Asia/Tokyo">Asia/Tokyo (UTC+9)</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                  <div className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="siteDescription">站点描述</Label>
                      <Textarea
                        id="siteDescription"
                        value={config.siteDescription}
                        onChange={(e) => setConfig(prev => ({ ...prev, siteDescription: e.target.value }))}
                        placeholder="请输入站点描述"
                        rows={3}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="language">系统语言</Label>
                      <Select value={config.language} onValueChange={(value) => setConfig(prev => ({ ...prev, language: value }))}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="zh-CN">简体中文</SelectItem>
                          <SelectItem value="en-US">English</SelectItem>
                          <SelectItem value="ja-JP">日本語</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              </TabsContent>

              {/* 安全设置 */}
              <TabsContent value="security" className="space-y-6 mt-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center">
                        <Shield className="w-5 h-5 mr-2" />
                        身份验证
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <Label>双因素认证</Label>
                          <p className="text-sm text-gray-500">增强账户安全性</p>
                        </div>
                        <Switch
                          checked={config.enableTwoFactor}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, enableTwoFactor: checked }))}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>会话超时时间（分钟）</Label>
                        <Input
                          type="number"
                          value={config.sessionTimeout}
                          onChange={(e) => setConfig(prev => ({ ...prev, sessionTimeout: parseInt(e.target.value) }))}
                          min="5"
                          max="480"
                        />
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center">
                        <Key className="w-5 h-5 mr-2" />
                        密码策略
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <Label>最小长度</Label>
                        <Input
                          type="number"
                          value={config.passwordPolicy.minLength}
                          onChange={(e) => setConfig(prev => ({
                            ...prev,
                            passwordPolicy: { ...prev.passwordPolicy, minLength: parseInt(e.target.value) }
                          }))}
                          min="6"
                          max="32"
                        />
                      </div>
                      <div className="space-y-3">
                        <div className="flex items-center justify-between">
                          <Label>要求大写字母</Label>
                          <Switch
                            checked={config.passwordPolicy.requireUppercase}
                            onCheckedChange={(checked) => setConfig(prev => ({
                              ...prev,
                              passwordPolicy: { ...prev.passwordPolicy, requireUppercase: checked }
                            }))}
                          />
                        </div>
                        <div className="flex items-center justify-between">
                          <Label>要求数字</Label>
                          <Switch
                            checked={config.passwordPolicy.requireNumbers}
                            onCheckedChange={(checked) => setConfig(prev => ({
                              ...prev,
                              passwordPolicy: { ...prev.passwordPolicy, requireNumbers: checked }
                            }))}
                          />
                        </div>
                        <div className="flex items-center justify-between">
                          <Label>要求特殊字符</Label>
                          <Switch
                            checked={config.passwordPolicy.requireSymbols}
                            onCheckedChange={(checked) => setConfig(prev => ({
                              ...prev,
                              passwordPolicy: { ...prev.passwordPolicy, requireSymbols: checked }
                            }))}
                          />
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </TabsContent>

              {/* 通知设置 */}
              <TabsContent value="notifications" className="space-y-6 mt-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center">
                      <Bell className="w-5 h-5 mr-2" />
                      通知偏好设置
                    </CardTitle>
                    <CardDescription>
                      选择您希望接收的通知类型
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Mail className="w-5 h-5 text-blue-600" />
                          <div>
                            <Label>邮件通知</Label>
                            <p className="text-sm text-gray-500">接收邮件提醒</p>
                          </div>
                        </div>
                        <Switch
                          checked={config.emailNotifications}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, emailNotifications: checked }))}
                        />
                      </div>
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Globe className="w-5 h-5 text-green-600" />
                          <div>
                            <Label>短信通知</Label>
                            <p className="text-sm text-gray-500">接收短信提醒</p>
                          </div>
                        </div>
                        <Switch
                          checked={config.smsNotifications}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, smsNotifications: checked }))}
                        />
                      </div>
                      <div className="flex items-center justify-between p-4 border rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Bell className="w-5 h-5 text-purple-600" />
                          <div>
                            <Label>推送通知</Label>
                            <p className="text-sm text-gray-500">浏览器推送</p>
                          </div>
                        </div>
                        <Switch
                          checked={config.pushNotifications}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, pushNotifications: checked }))}
                        />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 系统设置 */}
              <TabsContent value="system" className="space-y-6 mt-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center">
                        <Server className="w-5 h-5 mr-2" />
                        系统模式
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <Label>维护模式</Label>
                          <p className="text-sm text-gray-500">启用后用户无法访问系统</p>
                        </div>
                        <Switch
                          checked={config.maintenanceMode}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, maintenanceMode: checked }))}
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div>
                          <Label>调试模式</Label>
                          <p className="text-sm text-gray-500">显示详细的错误信息</p>
                        </div>
                        <Switch
                          checked={config.debugMode}
                          onCheckedChange={(checked) => setConfig(prev => ({ ...prev, debugMode: checked }))}
                        />
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center">
                        <Monitor className="w-5 h-5 mr-2" />
                        日志设置
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <Label>日志级别</Label>
                        <Select value={config.logLevel} onValueChange={(value) => setConfig(prev => ({ ...prev, logLevel: value }))}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="debug">Debug</SelectItem>
                            <SelectItem value="info">Info</SelectItem>
                            <SelectItem value="warning">Warning</SelectItem>
                            <SelectItem value="error">Error</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label>备份频率</Label>
                        <Select value={config.backupFrequency} onValueChange={(value) => setConfig(prev => ({ ...prev, backupFrequency: value }))}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="hourly">每小时</SelectItem>
                            <SelectItem value="daily">每天</SelectItem>
                            <SelectItem value="weekly">每周</SelectItem>
                            <SelectItem value="monthly">每月</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </TabsContent>

              {/* 备份管理 */}
              <TabsContent value="backup" className="space-y-6 mt-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center">
                        <Database className="w-5 h-5 mr-2" />
                        备份操作
                      </CardTitle>
                      <CardDescription>
                        创建和管理系统备份
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <Dialog open={showBackupDialog} onOpenChange={setShowBackupDialog}>
                        <DialogTrigger asChild>
                          <Button className="w-full">
                            <Download className="w-4 h-4 mr-2" />
                            创建新备份
                          </Button>
                        </DialogTrigger>
                        <DialogContent>
                          <DialogHeader>
                            <DialogTitle>创建系统备份</DialogTitle>
                            <DialogDescription>
                              这将创建包含所有数据和配置的完整系统备份
                            </DialogDescription>
                          </DialogHeader>
                          <div className="py-4">
                            <div className="flex items-center space-x-2 text-sm text-gray-600">
                              <Info className="w-4 h-4" />
                              <span>备份过程可能需要几分钟时间</span>
                            </div>
                          </div>
                          <DialogFooter>
                            <Button variant="outline" onClick={() => setShowBackupDialog(false)}>
                              取消
                            </Button>
                            <Button onClick={handleCreateBackup} disabled={loading}>
                              {loading ? '创建中...' : '开始备份'}
                            </Button>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>
                      <Button variant="outline" className="w-full">
                        <Upload className="w-4 h-4 mr-2" />
                        恢复备份
                      </Button>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader>
                      <CardTitle>备份历史</CardTitle>
                      <CardDescription>
                        最近的备份记录
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        {[
                          { date: '2024-01-15 10:30', size: '2.3 GB', status: 'success' },
                          { date: '2024-01-14 10:30', size: '2.1 GB', status: 'success' },
                          { date: '2024-01-13 10:30', size: '2.0 GB', status: 'success' },
                          { date: '2024-01-12 10:30', size: '1.9 GB', status: 'failed' }
                        ].map((backup, index) => (
                          <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                            <div className="flex items-center space-x-3">
                              {backup.status === 'success' ? (
                                <CheckCircle className="w-4 h-4 text-green-600" />
                              ) : (
                                <XCircle className="w-4 h-4 text-red-600" />
                              )}
                              <div>
                                <p className="text-sm font-medium">{backup.date}</p>
                                <p className="text-xs text-gray-500">{backup.size}</p>
                              </div>
                            </div>
                            <div className="flex space-x-2">
                              <Button variant="ghost" size="sm">
                                <Download className="w-3 h-3" />
                              </Button>
                              <Button variant="ghost" size="sm">
                                <Trash2 className="w-3 h-3 text-red-500" />
                              </Button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}